var Blog = require('../../model/blog');
var _ = require('underscore');

/**
 * Blog保存方法,或者更新
 */
exports.save = function(req, res) {
    var blogObj = req.body.blog;
     console.log(req.session.user._id)
    blogObj.author=req.session.user._id;
    var _blog = new Blog(blogObj)
    _blog.save(function(err) {
        if (err) {
            console.log(err);
        }
        res.redirect('/admin/blog');
    });
}

/**
 * blog更新
 */
exports.update = function(req, res) {
    var id = req.body.blog._id;
    var blogObj = req.body.blog;
    Blog.findOneByAttr({
        _id: id
    }, function(err, blog) {
        if (err) {
            console.log(err)
        }
       var _blog = _.extend(blog, blogObj)
        _blog.save(function(err) {
            if (err) {
                console.log(err);
            }
            res.redirect('/admin/blog');
        });
    })
}

/**
 * 后台查询出所有blog
 */
exports.fetch = function(req, res) {
    Blog.fetch(function(err, blogs) {
        if (err) {
            console.log(err);
        } else {
            console.log(req.session.user)
            res.render('admin/blog', {
                blogs: blogs
            })
        }
    });
}

/**
 * 文章编辑页
 */
exports.edit = function(req, res) {
    var id = req.params.id;
    Blog.findOneByAttr({
        _id: id
    }, function(err, blog) {
        if (err) {
            console.log(err)
        } else {
            res.render('admin/blogEdit', {
                blog: blog
            })
        }
    })
}
